package com.bj.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bj.util.GetHttpResponse;

/**
 * @author 作者 :ZYY
 * @version 创建时间：2016年12月2日 下午4:47:40 类说明
 */
public class Backjson extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		this.doPost(req, rsp);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8"); // 规定编码格式
		response.setContentType("text/html;charset=utf-8");
		String method = (String) request.getParameter("method");// 请求函数编号
		// 根据url参数，进入不同的处理方法
		if (method.equals("1")) {
			reRobInfo(request, response);
		} else if (method.equals("2")) {
			mapInfo(request, response);
		} else if (method.equals("3")) {
			robotStatus(request, response);
		} else if (method.equals("4")) {
			login(request, response);
		}
	}

	// 处理请求机器人信息
	public void reRobInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String json = "";
		try {
			String url = "http://118.178.188.27:8097/iot/data/audio";
			json = GetHttpResponse.getHttpResponse(url);
			String string = "[";
			for (int i = 0; i < 11; i++) {
				String str = json;
				str = str.substring(1, str.length() - 1) + ",";
				string += str;
			}
			json = string.substring(0, string.length() - 1) + "]";
			// System.out.println(string);

		} catch (Exception e) {
			e.printStackTrace();
		}
		PrintWriter pw = response.getWriter();
		pw.print(json);
		pw.close();
	}

	// 处理地图信息请求
	public void mapInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String json = "";
		try {
			String url = "http://118.178.188.27:8097/iot/data/geo/now";
			json = GetHttpResponse.getHttpResponse(url);

		} catch (Exception e) {
			e.printStackTrace();
		}
		PrintWriter pw = response.getWriter();
		pw.print(json);
		pw.close();
	}

	// 处理机器人状态请求
	public void robotStatus(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String json = "";
		try {
			String url = "http://118.178.188.27:8097/iot/data/stat/now";
			json = GetHttpResponse.getHttpResponse(url);

		} catch (Exception e) {
			e.printStackTrace();
		}
		PrintWriter pw = response.getWriter();
		pw.print(json);
		pw.close();
	}
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("index.html").forward(request, response);
	}

}
